<?php
/**
 * User: Kris
 * Date: 1/12/12
 * Time: 8:10 PM
 */

require_once APPPATH . 'core/controller.php';

class CategoryController extends Controller
{

    public function __construct()
    {

        parent::__construct();
        $this->data['styles'][] = '/public/css/category.css';
    }

    public function view($categoryName)
    {
        $topThree = new TopThreePosts();
        $this->data['currentCategory'] = $categoryName;

        $posts = $this->em->createQuery("SELECT p FROM Post p JOIN p.category c WHERE c.name = '".$categoryName."' ORDER BY p.id DESC")->setMaxResults(12);
        $this->data['latestPosts'] = $posts->getResult();

        /**
         * @var $user User
         */
        $user = $this->em->find('User', $this->session->userdata('userId'));
        $category = $this->em->getRepository('Category')->findOneBy(array('name' => $categoryName));

        $this->data['userIsSubscribed'] = false;
        if($user != null && $category != null)
        {
            $this->data['userIsSubscribed'] = $user->getCategorySubscriptions()->contains($category);
        }

        foreach ($posts->getResult() as $post) {
            $topThree->validateAndAdd($post);
         }
        $this->data['topThree'] = $topThree->getTopThree();

        $this->parser->parse("category/index.tpl", $this->data);
    }
}
